<template>
  <div class="my-content">
    <div class="l-item">
      <span>当前栏目：根目录</span>
      <Dropdown
        trigger="hover"
        @on-click="addContent"
      >
        <Button class="add-content-btn"
                type="primary"
        >
          <Icon type="plus"></Icon>
          添加内容
        </Button>
        <DropdownMenu slot="list">
          <DropdownItem
            v-for="item in dropDownList" :key="item.id" :name="item.id"
          >{{item.name}}
          </DropdownItem>
        </DropdownMenu>
      </Dropdown>
    </div>
    <div class="l-item" style="display: none;">
      <Select
        style="width:200px;margin-right: 10px;"
        @on-change="changeType"
        :filterable=false
        placeholder="所有类型">
        <Option v-for="item in allType" :value="item.name" :key="item.key">{{item.name}}</Option>
      </Select>
      <Select
        style="width:200px;margin-right: 10px;"
        filterable
        @on-change="changeStatus"
        :filterable=true
        placeholder="所有状态">
        <Option v-for="item in allStatus" :value="item.name" :key="item.key">{{item.name}}</Option>
      </Select>
      <Select
        style="width:200px;margin-right: 10px;"
        @on-change="changeOrder"
        :filterable='false'
        placeholder="发布时间升序">
        <Option v-for="item in allOrders" :value="item.name" :key="item.key">{{item.name}}</Option>
      </Select>
    </div>
    <div class="table-data">
      <Table
        :border=false
        class="table-style"
        :columns="columns"
        :data="tableData"
        ref="selection"
      ></Table>
      <Page
        class="page-style"
        show-sizer
        show-elevator
        :page-size=pageSize
        :total="totalRecords"
        @on-change="pageChange"
        @on-page-size-change="pageSizeChange"
      ></Page>
      <Modal
        width="520"
        title="警告"
        v-model="showModel"
        @on-ok="modalHandler"
        @on-cancel="modalInfo={}"
      >
        <Icon type="close-circled" size="24" color="#f56c6c"></Icon>
        <span style="font-size: 14px;margin-left: 10px;">{{modalInfo.type==='del'?'是否确认删除？':'是否确认编辑？'}}</span>
      </Modal>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        allType: [
          {name: '所有类型', id: 't0'},
          {name: '普通', id: 't1'},
          {name: '图文', id: 't2'},
          {name: '焦点', id: 't3'},
          {name: '头条', id: 't4'}],
        allStatus: [
          {name: '所有状态', id: 's1'},
          {name: '待审', id: 's2'},
          {name: '审核通过', id: 's3'},
          {name: '草稿', id: 's4'},
          {name: '退回', id: 's5'}],
        allOrders: [{name: 'id升序', id: 'o1'},
          {name: 'id降序', id: 'o2'},
          {name: '发布时间升序', id: 'o3'},
          {name: '发布时间降序', id: 'o4'},
          {name: '总点击量升序', id: 'o5'},
          {name: '总点击量降序', id: '06'},
        ],
        dropDownList: [{name: '新闻', id: 'news'}, {name: '招聘', id: 'recruit'}],
        type: {
          typeId: '',
          typeName: ''
        },
        status: {
          statusId: '',
          statusName: ''
        },
        order: {
          orderId: '',
          orderName: ''
        },
        columns: [{type: 'selection', width: 80}, {title: 'id', key: 'id'}, {title: '标题', key: 'title'}, {
          title: '置顶', key: 'is_top'
        }, {title: '栏目名称', key: 'module_name'}, {title: '发布者', key: 'author'}, {title: '点击', key: 'clickTime'},
          {title: '发布时间', key: 'gmt_publish_time'},
          {title: '状态', key: 'is_draft'},
          {
            title: '操作', key: 'actionStatus', render: (h, params) => {
              return h('div', [
                h('Icon', {
                  props: {
                    type: 'edit',
                  },
                  style: {
                    display: 'inline-block',
                    width: '24px',
                    height: '24px',
                    lineHeight: '24px',
                    marginRight: '10px',
                    textAlign: 'center',
                    cursor: 'pointer',
                    borderRadius: '4px',
                    color: '#fff',
                    backgroundColor: '#17d57e'
                  },
                  on: {
                    click: () => {
                      this.showModel = true;
                      this.modalInfo = {...params, type: 'edit'};
                    }
                  }
                }),
                h('Icon', {
                  props: {
                    type: 'close',
                  },
                  style: {
                    display: 'inline-block',
                    width: '24px',
                    height: '24px',
                    lineHeight: '24px',
                    textAlign: 'center',
                    cursor: 'pointer',
                    borderRadius: '4px',
                    color: '#fff',
                    backgroundColor: '#ff8b53'
                  },
                  on: {
                    click: () => {
                      this.showModel = true;
                      this.modalInfo = {...params, type: 'del'};
                    }
                  }
                })
              ]);
            }
          }],
        tableData: [], // 以下是table列表的一些参数
        totalRecords: 1,
        page: 1,
        pageSize: 10,
        showModel: false,//是否显示删除新闻 modal框
        modalInfo: {},// 被删除行的详细信息，从 上述render函数中获取
      }
    },
    methods: {
      changeType(value) {
        this.type = {
          typeId: [this.allType, this.allStatus, this.allOrders].map(item => {
            return item.find(x => x.name === value)
          }).find(d => d)['key'],
          typeName: (value.indexOf('所有') > -1) ? '' : value
        };
        this.getNewList()
      },
      changeStatus(value) {
        this.status = {
          statusId: [this.allType, this.allStatus, this.allOrders].map(item => {
            return item.find(x => x.name === value)
          }).find(d => d)['key'],
          statusName: (value.indexOf('所有') > -1) ? '' : value
        };
        this.getNewList()
      },
      changeOrder(value) {
        this.order = {
          orderId: [this.allType, this.allStatus, this.allOrders].map(item => {
            return item.find(x => x.name === value)
          }).find(d => d)['key'],
          orderName: ''
        };
        this.getNewList()
      },
      getNewList() {
        let data = {
          page: this.page,
          page_size: this.pageSize,
          type: this.type.typeName,
          status: this.status.statusName,
          order: this.order.orderName
        };

        this.$axios.post(this.$store.getters.getUrl('allNewsList'), data).then(res => {
          if (res.data.error_code === 0) {

            res.data.data && (this.tableData = this.handleData(res.data.data.rows));
            res.data.data && (this.totalRecords = res.data.data.total_records);
          }
        })
      },
      handleData(data) {
        return data.map(item => {
          // 处理 置顶
          if (!item.is_top) {
            item.is_top = '否'
          } else {
            item.is_top = `置顶至：${item.gmt_top_time}`
          }
          // 处理状态
          if (!item.is_draft) {
            item.is_draft = '已发布'
          } else {
            item.is_draft = '草稿'
          }
          // 处理栏目名称
          item.module_name = item.module_name.join('/')
          return item
        })
      },
      pageChange(value) {
        this.page = value;
        this.getNewList()
      },
      pageSizeChange(value) {
        this.pageSize = value;
        this.getNewList()
      },
      handleColumns() {
        this.columns.map(item => item['align'] = 'center')
      },
      modalHandler() {
        let {id} = this.modalInfo.row,
          {type} = this.modalInfo;
        document.body.style = '';// 这是iView组件留下的一个bug
        (type === 'del') && this.$axios.post(this.$store.getters.getUrl('deleteSingleNews'), {id}).then(res => {
          if (res.data.error_code === 0) {
            this.$Message.success({
              content: '删除成功！'
            });
            this.getNewList();
          }
        });
        (type === 'edit') && this.$router.push({name: 'NewsCorrect', params: {id}});
      },
      addContent(name) {
        console.log('name:', name)
        switch (name) {
          case 'news':
            this.$router.push({name: 'NewsEdit'});
            break;
          case 'recruit':
            this.$router.push({name: 'RecruitEdit'});
            break;
        }
      },
      // 编辑---跳转至编辑页面，进行内容回显
      goEditPage(params) {
        let {id} = this.modalInfo.row;
      }
    },
    created() {
      this.getNewList();
      this.handleColumns();
    },
    mounted() {
      this.$store.dispatch('setBreadcrumbInfo', [{name: '新闻'},
        {name: '新闻列表', routeName: 'NewsList'}])
    }
  }
</script>

<style lang='less' type='text/less' scoped>
  .my-content {
    height: 100%;
    background-color: #fff;
    .l-item {
      height: 50px;
      line-height: 50px;
      padding: 0 24px;
      font-size: 14px;
      border-bottom: 1px #e7ecf3 dashed;
    }
    .add-content-btn {
      margin-left: 25px;
    }
    .table-style {
      margin-top: 10px;
      border: none
    }
    .page-style {
      text-align: right;
      margin: 20px;
    }
  }
</style>
